import {Component, OnInit, ViewChild} from '@angular/core';
import {tuikeSystemUrl} from "../../../../config/api";
import {Router} from "@angular/router";
import {CategoryService} from "../../category/category.service";
import {HttpService} from "../../../lib/service/http.service";
import {Headers, RequestOptions} from "@angular/http";
import {ModalDirective} from "ngx-bootstrap";
import {LoginService} from "../../../lib/service/tuike-login.service";

@Component({
  selector: 'app-hot',
  templateUrl: './hot.component.html',
  styleUrls: ['./hot.component.scss'],
  providers: [CategoryService]

})
export class HotComponent implements OnInit {
  _isSpinning = false;
  pageSize = 20;
  page = 1;
  totalItems = 0;
  keywordList = [];
  keywordTotal = 0;
  categories = [];
  addStatus = false;
  type = 'error';
  isShow = false;
  message = '';
  editKey = '';
  editId = '';
  editSort = '';
  deleteId = '';
  editTop;
  editShow;
  key = '';
  sort;
  show = '1';
  top = '1';
  sortError = false;
  nameError = false;
  canVisit = false;
  canVisit1 = false;
  canVisit2 = false;

  @ViewChild('editModal') public editModal: ModalDirective;
  @ViewChild('addModal') public addModal: ModalDirective;
  @ViewChild('confirmModal') public confirmModal: ModalDirective;

  constructor(private router: Router,
              private httpService: HttpService,
              private categoryService: CategoryService,
              private loginService: LoginService
              ) {
  }


  ngOnInit() {
    this.canVisit = this.loginService.canVisitCheck('add_hot');
    this.canVisit1 = this.loginService.canVisitCheck('edit_hot');
    this.canVisit2 = this.loginService.canVisitCheck('delete_hot');
    this.getHotKeyList(1);
  }

  goKeyword() {
    this.router.navigate(['tuike/keyword/add']);
  }

  showEditModal(item) {
    this.editId = item.id;
    this.editKey = item.key;
    this.editSort = item.sort;
    this.editShow = item.show;
    this.editTop = item.top;
    this.editModal.show();
  }

  cancel() {
    this.nameError = false;
    this.sortError = false;
    this.key = '';
    this.sort = '';
    this.show = '1';
    this.top = '1';
    this.addModal.hide();
  }

  checkName(e) {
    console.log(e);
    if (!e.replace(/\s/g, "")) {
      this.nameError = true;
    } else {
      this.nameError = false;
    }
  }

  checkSort(e) {
    if (!/^[1-9]\d*|0$/.test(e + '')) {
      this.sortError = true;
    } else {
      this.sortError = false;
    }
  }

  editCancel() {
    this.nameError = false;
    this.sortError = false;
    this.editModal.hide();
  }

  editkeyWord() {
    let key = this.editKey.replace(/(^\s+)|(\s+$)/g, "");
    if (key == '') {
      this.type = 'error';
      this.message = '关键词不能为空';
      this.isShow = true;
      return;
    }  else if (!/^[1-9]\d*|0$/.test(this.editSort + '')) {
      this.type = 'error';
      this.message = '关键词排序有误';
      this.isShow = true;
      return;
    } else {
      const url = `${tuikeSystemUrl}/api/v1/admin/task_hot_key_show/update_key`;
      const headers = new Headers({'Content-Type': 'application/json'});
      const options = new RequestOptions({headers: headers});
      const body = JSON.stringify({'id': this.editId, 'key': this.editKey,'sort' : this.editSort,top: this.editTop, show: this.editShow});
      this.httpService.httpPostAuth(url, body, options).subscribe(rs => {
        if (rs.code === 200) {
          this.type = 'success';
          this.message = '修改成功';
          this.isShow = true;
          this.editModal.hide();
          setTimeout(() => {
            this.getHotKeyList(this.page);
          },500);
        } else {
          this.type = 'error';
          this.message = rs.message;
          this.isShow = true;
        }
      })
    }
  }

  getHotKeyList(page) {
    this._isSpinning = true;
    const url = `${tuikeSystemUrl}/api/v1/admin/task_hot_key_show/key_list?page=${page}&pageSize=${this.pageSize}`;
    this.httpService.httpGetAuth(url).subscribe(res => {
      if (res.code === 200) {
        this.keywordList = res.data.data;
        this.totalItems = res.data.total;
        this._isSpinning = false;
      }
    })
  }

  addKeyWord() {
    if(this.nameError) {
      this.type = 'error';
      this.message = '关键词名字不能为空';
      this.isShow = true;
    } else if (this.sortError) {
      this.type = 'error';
      this.message = '关键词排序有误';
      this.isShow = true;
    }
    if(!this.nameError && !this.sortError) {
      const url = `${tuikeSystemUrl}/api/v1/admin/task_hot_key_show/add_key`;
      const headers = new Headers({'Content-Type': 'application/json'});
      const options = new RequestOptions({headers: headers});
      const body = JSON.stringify({'key': this.key, 'sort': this.sort, top :this.top, show: this.show});
      this.httpService.httpPostAuth(url,body,options).subscribe(res => {
        if(res.code === 200) {
          this.type = 'success';
          this.message = '添加成功';
          this.isShow = true;
          this.sort = '';
          this.key = '';
          this.show = '1';
          this.top = '1';
          this.addModal.hide();
          this.page = 1;
          setTimeout(() => {
            this.getHotKeyList(this.page);
          }, 100);
        } else {
          this.type = 'error';
          this.message = res.message;
          this.isShow = true;
        }
      })
    };
  }

  delete() {
    const url = `${tuikeSystemUrl}/api/v1/admin/task_hot_key_show/delete_key`;
    const headers = new Headers({'Content-Type': 'application/json'});
    const options = new RequestOptions({headers: headers});
    const body = JSON.stringify({'id':this.deleteId});
    this.httpService.httpPostAuth(url, body, options).subscribe(rs => {
      if (rs.code === 200) {
        this.type = 'success';
        this.message = '删除成功';
        this.isShow = true;
        this.confirmModal.hide();
        this.page = 1;
        this.getHotKeyList(1);
      } else {
        this.type = 'error';
        this.message = rs.message;
        this.isShow = true;
      }
    })
  }

  goEdit(id) {
    this.router.navigate(['tuike/keyword/add'], {
      queryParams: {
        id: id
      }
    })
  }

  showConfirmModal(id) {
    this.deleteId = id;
    this.confirmModal.show();
  }

  showAddModal() {
    this.addModal.show();
  }

  pageChanged(event: any): void {
    window.scrollTo(0, 0);
    this.getHotKeyList(event.page);
  }
}
